package com.tuyan.aixiang;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.ezviz.opensdk.auth.OnAuthCallBack;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.tuyan.aixiang.api.HttpClient;
import com.tuyan.aixiang.api.helper.ResultTransformer;
import com.tuyan.aixiang.api.helper.RxSchedulers;
import com.tuyan.aixiang.common.AppData;
import com.tuyan.aixiang.common.Constant;
import com.tuyan.aixiang.common.M;
import com.tuyan.aixiang.common.StorageKey;
import com.tuyan.aixiang.model.YsTokenResult;
import com.tuyan.aixiang.util.StorageUtil;
import com.tuyan.aixiang.util.ToastUtil;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.bean.EZAccessToken;

import java.util.Date;
import java.util.HashMap;

public class MainApplication extends Application {

    private static final String TAG = "MainApplication";


    private static Context mContext;

    private int mActivityAmount = 0;
    private static boolean mIsForeground = false;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
//        ApiManager.getInstance().init();
//        initAppData();
        initTBS();
        initYsSDK();
        initPushSdk(this);
    }

    private void initTBS() {
        registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
                Log.e(TAG, "==================QbSDK init finish");

            }

            @Override
            public void onViewInitFinished(boolean b) {
                Log.e(TAG, "==================QbSDK init " + b);

            }
        };
        // 在调用TBS初始化、创建WebView之前进行如下配置
        HashMap map = new HashMap();
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
        QbSdk.initTbsSettings(map);
        QbSdk.setDownloadWithoutWifi(true);
        QbSdk.initX5Environment(getApplicationContext(), cb); // 初始化X5
    }

    private void initYsSDK() {

        YsTokenResult tokenResult =  StorageUtil.getObject(StorageKey.YS_TOKEN, YsTokenResult.class);
        if(null != tokenResult) {
//            String ysToken = tokenResult.getAccessToken();
            Long expire = tokenResult.getExpireTime();
            if(new Date().getTime() > expire - 1000 * 60 * 60 *24) {
                refreshYsToken();
            } else {
                initEzSDK(tokenResult);
            }
        } else  {
            refreshYsToken();
        }
    }

    private void initEzSDK(YsTokenResult tokenResult) {
        EZOpenSDK.initSDK(this, Constant.YS_APP_KEY);
        EZOpenSDK.showSDKLog(BuildConfig.DEBUG);
        EZOpenSDK.enableP2P(false);
        EZOpenSDK.setAuthCallBack(new OnAuthCallBack() {
            @Override
            public void onAuthSuccessCallBack(EZAccessToken ezAccessToken) {
                Log.d(TAG, "ezAccessAuth Success " + ezAccessToken);
            }

            @Override
            public void onNeedAuthAccessToken() {
                Log.d(TAG, "ezAccessAuth NeedAuth");
            }
        });
        String atoken = tokenResult.getAccessToken();
        StorageUtil.setObject(StorageKey.YS_TOKEN, tokenResult);
        EZOpenSDK.setAccessToken(atoken);
        AppData.setYsToken(atoken);

    }

    @SuppressLint("CheckResult")
    private void refreshYsToken() {
        StorageUtil.remove(StorageKey.YS_TOKEN);
        HttpClient.getYsApi().getToken(M.m().put("appKey", Constant.YS_APP_KEY).put("appSecret", Constant.YS_APP_SEC))
                .compose(RxSchedulers.io_main()).compose(ResultTransformer.handleResult())
                .subscribe(data -> {
                   initEzSDK(data.get());
                }, throwable -> {
                    ToastUtil.makeShort("获取萤石AccessToken失败");
                    refreshYsToken();
                });

    }



    /**
     * Activity 生命周期监听，用于监控app前后台状态切换
     */
    ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        }

        @Override
        public void onActivityStarted(Activity activity) {
            if (!mIsForeground) {
                mIsForeground = true;
            }
            mActivityAmount++;
        }

        @Override
        public void onActivityResumed(Activity activity) {
        }

        @Override
        public void onActivityPaused(Activity activity) {
        }

        @Override
        public void onActivityStopped(Activity activity) {
            mActivityAmount--;
            if (mActivityAmount == 0) {
                mIsForeground = false;
            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
        }
    };



    static CloudPushService pushService;
//
    private void initPushSdk(final Context applicationContext) {
        this.createNotificationChannel();
        PushServiceFactory.init(applicationContext);
        pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.i(TAG, "init cloudchannel success");
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.e(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });

    }

    public static void bindAccount(String account) {
        if (null == pushService) return;
        pushService.bindAccount(account, new CommonCallback() {
            @Override
            public void onSuccess(String s) {
                Log.d(TAG, "MessagePush bindAccount success");
            }

            @Override
            public void onFailed(String s, String s1) {
                Log.e(TAG, "MessagePush bingAccount failed");
            }
        });
    }

    public static void unBindAccount() {
        if (null == pushService) return;
        pushService.unbindAccount(new CommonCallback() {
            @Override
            public void onSuccess(String s) {
                Log.d(TAG, "MessagePush unBindAccount success");

            }

            @Override
            public void onFailed(String s, String s1) {
                Log.e(TAG, "MessagePush unBindAccount failed");

            }
        });
    }

//
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id
            String id = "2";
            // 用户可以看到的通知渠道的名字.
            CharSequence name = "aixiang push";
            // 用户可以看到的通知渠道的描述
            String description = "aixiang push service";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
//            mChannel.setSound();
            // 配置通知渠道的属性
            mChannel.setDescription(description);
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            //最后在notificationmanager中创建该通知渠道
            mNotificationManager.createNotificationChannel(mChannel);
        }
    }


    public static boolean isForeground() {
        return mIsForeground;
    }

    public static Context getAppContext() {
        return mContext;
    }
}
